Event.observe ( window, 'load', bootstrap );

var numbers = $R( 1, 9 );

function          line_node ( i ) { return $(          "line_" + i ) }
function specification_node ( i ) { return $( "specification_" + i ) }

function affected_value ( i ) {
  return specification_node ( i ).value !== "-";
}
function unaffected_value ( i ) {
  return ! affected_value ( i );
}
function reachable_value ( i ) {
  return line_node ( i ).style["display"] !== "none";
}
function unreachable_value ( i ) {
  return ! reachable_value ( i );
}

function handle_specification_change ( number ) {
  var specification_id = "specification_" + number;
  var     tag_id = specification_id + "_tag";

  $( specification_id ).onchange = function () {
    update_specification_tags ( $( specification_id ).value, tag_id );
        
    if ( numbers.filter ( reachable_value ).all ( affected_value ) ) {
      var next_number = numbers.find ( unreachable_value );
      
      if ( next_number ) {
        line_node ( next_number ).show ();
      }
    }
    else {
      var unaffected_numbers = numbers.filter ( reachable_value ).filter ( unaffected_value );
      
      if ( unaffected_numbers.size () > 1 ) {
        unaffected_numbers.pop ();
        
        unaffected_numbers.each ( function ( i ) { line_node ( i ).hide () } );
      }
    }
  };
}

function bootstrap () {
  numbers.each ( function ( number ) { handle_specification_change ( number ) } );
}
